package com.cskaoyan.mall.utils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HttpUtils {
    /**
     * 专门用来去读取请求体里面的参数（字符）数据
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestBody(HttpServletRequest request) throws IOException{
//取出请求参数 --- 取出请求体里面的数据
        //此时无法使用request.getParamater  --->只能获取 key=value & key1=value1
        ServletInputStream inputStream = request.getInputStream(); //获取request 请求的InputStream，转到bytes中去
        //形成JSON字符串
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int length = 0;
        while((length = inputStream.read(bytes))!= -1){
            outputStream.write(bytes,0,length);
        }
        //requestBody ---- 就是json字符串 ---->转成 Java对象来处理
        return outputStream.toString("utf-8");
    }
}
